package com.tianji.learning.service.impl;

import com.tianji.common.utils.DateUtils;
import com.tianji.common.utils.UserContext;
import com.tianji.learning.domain.po.PointsRecord;
import com.tianji.learning.domain.vo.PointsStatisticsVO;
import com.tianji.learning.mapper.PointsRecordMapper;
import com.tianji.learning.service.IPointsRecordService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

/**
 * <p>
 * 学习积分记录，每个月底清零 服务实现类
 * </p>
 *
 * @author wangyuqing
 * @since 2024-08-29
 */
@Service
public class PointsRecordServiceImpl extends ServiceImpl<PointsRecordMapper, PointsRecord> implements IPointsRecordService {

    /**
     * 1.获取当前用户今日积分情况
     *
     * @return
     */
    @Override
    public List<PointsStatisticsVO> queryTodayMyPoints() {
        //1.获取用户Id,时间，构造查询条件
        Long UserId = UserContext.getUser();
        LocalDateTime now = LocalDateTime.now();
        LocalDateTime start = DateUtils.getDayStartTime(now);
        LocalDateTime end = DateUtils.getDayEndTime(now);
        //2.进行查询，根据积分类型进行分组
        List<PointsRecord> list = this.query()
                .select("`type`,sum(points) as points")
                .eq("user_id", UserId)
                .between("create_time", start, end)
                .groupBy("`type`").list();
        if (list.isEmpty()) {
            return Collections.emptyList();
        }
        //3.封装返回
        List<PointsStatisticsVO> voList = new ArrayList<>(list.size());
        for (PointsRecord pointsRecord : list) {
            PointsStatisticsVO vo = new PointsStatisticsVO();
            vo.setPoints(pointsRecord.getPoints());
            vo.setType(pointsRecord.getType().getDesc());
            vo.setMaxPoints(pointsRecord.getType().getMaxPoints());
            voList.add(vo);
        }
        return voList;
    }
}
